const fs = require('fs');
const fse = require('fs-extra')

// 备份文件
function backUpFiles(filename, data) {
    fs.mkdirSync('bak', { recursive: true });
    fs.writeFileSync(`./bak/${filename}.bak`, data, 'utf-8', (err) => {
        if (err) {
            console.error(`[ERROR] Failed to back up ${filename}. ${err}`);
        }
    });
}

function filterFileByExt(dir, exts = [], target) {
    let files = fs.readdirSync(dir);
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        let stat = fs.lstatSync(`${dir}\\${file}`);
        if (stat.isDirectory()) {
            filterFileByExt(`${dir}\\${file}`, exts, `${target}\\${file}`);
        } else {
            for (let j = 0; j < exts.length; j++) {
                let ext = exts[j];
                if (file.split('.').pop().toLowerCase() === ext.trim().toLowerCase()) {
                    try {
                        fse.copySync(`${dir}\\${file}`, `${target}\\${file}`);
                    } catch (err) {
                        console.error(`[ERROR] Failed to copy ${file} to ${target}`)
                    }
                    break;
                }
            }
        }
    }
}

const MATN_PATH = '../tester/harmony/react_native_openharmony/src/main';

// 替换cmakelist
fs.readFile(`${MATN_PATH}/cpp/CMakeLists.txt`, 'utf8', (err, data) => {
    if (err) {
        console.error(`[ERROR] Failed to read CMakeLists.txt. ${err}`);
        return;
    }
    // 备份CMakeLists.txt
    backUpFiles('CMakeLists.txt', data);
    // 替换
    const replaceData = data.replace(/\bset\b/, `
        project(rnoh_semi)
        set(RNOH_CPP_DIR "\${CMAKE_CURRENT_SOURCE_DIR}")
        set(WITH_HITRACE_SYSTRACE 1)
        add_compile_definitions(WITH_HITRACE_SYSTRACE)
        set`).replace(/\brnoh\b/g, 'rnoh_semi');
    fs.writeFile(`${MATN_PATH}/cpp/CMakeLists.txt`, replaceData, 'utf8', (err) => {
        if (err) {
            console.error(`[ERROR] Failed to write CMakeLists.txt. ${err}`);
            return;
        }
    });
});
// 替换build-profile.json5
fs.readFile(`${MATN_PATH}/../../build-profile.json5`, 'utf8', (err, data) => {
    if (err) {
        console.error(`[ERROR] Failed to read build-profile.json5. ${err}`);
        return;
    }
    // 备份build-profile.json5
    backUpFiles('build-profile.json5', data);
    // 替换
    fse.copySync(`./resource/build-profile.json5`, `${MATN_PATH}/../../build-profile.json5`);
});
// 补充RNONOther
fse.copySync(`./resource/RNOHOther.cpp`, `${MATN_PATH}/include/RNOHOther.cpp`);
// 筛选出所有头文件
filterFileByExt(`${MATN_PATH}/cpp`, ['h', 'hpp', 'ipp'], `${MATN_PATH}/include`);
// 同步其他文件
const sourceList = [
    'third-party/folly/CMake/folly-config.h.cmake',
    'third-party/folly/folly/lang/SafeAssert.cpp',
    'RNOHAppNapiBridge.cpp',
]
sourceList.forEach((source) => {
    try {
        fse.copySync(`${MATN_PATH}/cpp/${source}`, `${MATN_PATH}/include/${source}`);
    } catch (error) {
        console.error(`[ERROR] Failed to copy ${source} to ${MATN_PATH}/include/${source}`);
    }
});